package falcon.script;

import falcon.common.Bash;
import falcon.common.Errno;

public final class FalconLangFuncCall {

	public static int call(String path, String[] args, String[] rets) {
		if (args.length < 1) {
			return Errno._INVALID_ARGUMENT;
		}
		// 连接字符串格式 user@host:port
		String connection = args[0];
		int userSplit = connection.indexOf('@');
		if (userSplit < 0) {
			return Errno._INVALID_ARGUMENT;
		}
		String user = connection.substring(0, userSplit);
		int hostSplit = connection.indexOf(':');
		if (hostSplit < userSplit) {
			return Errno._INVALID_ARGUMENT;
		}
		String host = connection.substring(userSplit + 1, hostSplit);
		String portString = connection.substring(userSplit + 1);
		if (!portString.matches("^\\d+$")) {
			return Errno._INVALID_ARGUMENT;
		}
		int port = Integer.parseInt(portString);
		// 获取密码
		String password = null;
		StringBuilder sb = new StringBuilder(512);
		// 脚本路径
		sb.append(path);
		sb.append(' ');
		// 参数
		for (int i = 1; i < args.length; i ++) {
			sb.append(args[i]);
			sb.append(' ');
		}
		String command = sb.toString();
		Bash bash = new Bash(command, host, port, user, password);
		sb = new StringBuilder(1024);
		bash.bindOutput(sb);
		int errno = bash.execute();
		if (errno != Errno.SUCCESS) {
			return errno;
		}
		String line = sb.toString().split("\n")[0];
		fillRetValue(line, rets);
		return Errno.SUCCESS;
	}
	
	private static void fillRetValue(String line, String[] rets) {
		int i = 0;
		int begin = 0;
		int end = begin;
		while (begin < line.length()) {
			for (int j = begin; j < line.length(); j ++) {
				char ch = line.charAt(j);
				if (ch == ' ' && ch == '\t') {
					end = j;
					break;
				}
			}
			if (end - begin > 0) {
				rets[i] = line.substring(begin, end);
				i ++;
				if (i >= rets.length) {
					return;
				}
			}
			begin = end + 1;
		}
		for (int x = i; x < rets.length; x ++) {
			rets[x] = "";
		}
	}
}
